/*
** communication.c for  in /home/gomes_m//my-project-a-moi/client
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Sun Jul 28 14:00:55 2013 mickael gomes
** Last update Wed Jul 31 01:15:47 2013 mickael gomes
*/

#include		<stdlib.h>
#include		<stdio.h>
#include		<unistd.h>
#include		<struct.h>
#include		<prototypes.h>

t_func			func[] =
  {
    {&get_fork, "ls"},
    {&get_fork, "mv"},
    {&get_fork, "cp"},
    {&get_fork, "pwd"},
    {&get_fork, "mkdir"},
    {&get_fork, "touch"},
    {&get_fork, "rm"},
    {&get_fork, "rmdir"},
    {&transfert, "dl"},
    {&my_cd, "cd"},
  };

int			check_cmd(char *buff)
{
  int			i = 0;

  while (i < 10)
    {
      if (my_strcmp(buff, func[i].flag))
	i++;
      else
	return (i);
    }
  return (-1);
}

void			send_cmd(char *buff, t_socket *socket)
{
  xwrite(socket->fd, buff, my_strlen(buff));
}

void			server_response(t_socket *socket, t_cmd *cmd)
{
  int			len;

  if ((len = read(socket->fd, cmd->response, 1024)) > 0)
    {
      cmd->response[len] = 0;
      if (cmd->cmd != NULL && my_strcmp(cmd->cmd, "dl"))
	printf("%s", cmd->response);
    }
  else
    my_putstr(2, "Read error.\n", 1);
}

int			treat_local(char *buff, t_cmd *cmd)
{
  if (!my_strcmp("local", buff) && cmd->local == 0)
    {
      cmd->local = 1;
      my_putstr(2, "Local mode activated.\n", 0);
      return (1);
    }
  if (!my_strcmp("local", buff) && cmd->local == 1)
    {
      my_putstr(2, "Local mode already activated.\n", 0);
      return (1);
    }
  if (!my_strcmp("online", buff) && cmd->local == 1)
    {
      cmd->local = 0;
      my_putstr(2, "Online mode activated.\n", 0);
      return (1);
    }
  if (!my_strcmp("online", buff) && cmd->local == 0)
    {
      my_putstr(2, "Online  mode already activated.\n", 0);
      return (1);
    }
  return (0);
}

void			get_cmd(t_cmd *cmd, t_socket *socket)
{
  char			*buff;

  buff = xmalloc(1024 * sizeof(char));
  xread(0, buff, 1024);
  buff = treat_buff(buff);
  cmd->complete_cmd = buff;
  cmd->cmd = get_first_part(buff);
  if (treat_local(buff, cmd) == 1)
    return ;
  if ((cmd->pos = check_cmd(cmd->cmd)) == -1)
    {
      if (!my_strcmp(cmd->cmd, "exit"))
	exit(EXIT_SUCCESS);
      return (my_putstr(2, "Command not found.\n", 0));
    }
  cmd->arguments = get_remains(buff);
  cmd->cmd_tab = my_str_to_wordtab(buff);
  if ((cmd->local == 1 && cmd->pos != 0 && cmd->pos != 8 && cmd->pos != 9)
      || cmd->local == 0)
    {
      send_cmd(buff, socket);
      server_response(socket, cmd);
    }
  if (cmd->local == 1)
    func[cmd->pos].f(cmd, socket);
}
